package com.example.server.security;

import com.example.common.vo.RespBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class DefaultSessionBasedAuthenticateInterceptor implements HandlerInterceptor {

    @Value("${yeb.security.enable-authenticated-annotation}")
    private boolean enableAuthenticated;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {

            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Authenticated methodAnnotation = handlerMethod.getMethodAnnotation(Authenticated.class);

            if (!enableAuthenticated || (enableAuthenticated && methodAnnotation != null) ) {
                HttpSession session = request.getSession();
                Object auth = session.getAttribute("auth");

                if (auth == null) {
                    // 4xx 认证或者授权得异常
                    throw RespBean.AUTH_FAILED_ERROR_401.toException();
                }
            }
        }

        // 放行当前得请求
        return true;
    }
}
